﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using TongHopBookFlightDAO;
using TongHopBookFlightDAO.DAO;

namespace TongHopBookFlightCores.Cores
{
    public class RutTrichTrangAirMekong
    {
        string strURL = Constants.AIRMEKONG_URL;
        int maHangKhong = HangHangKhongDAO.SelectByName(Constants.AIRMEKONG_NAME).HangHangKhongID;

        public void TimChuyenBayTheoMotChieu(string diemDi, string diemDen, DateTime ngayDi)
        {
            int ngay= ngayDi.Day;
            string strThangNamDi = ngayDi.Year + "-" + ngayDi.Month;

            string postString = TaoPostString(diemDi, diemDen, ngay, strThangNamDi);

            HtmlAgilityPack.HtmlDocument dom = GuiYeuCauLenWeb(postString);

            //Lấy table lưu thông tin các chuyến bay tìm thấy được
            HtmlAgilityPack.HtmlNodeCollection nodeCollectionChuyenBay = dom.DocumentNode.SelectNodes(
                "//*[@id='availabilityTable0']/tr");

            if (nodeCollectionChuyenBay != null)
            {
                for (int i = 2; i < nodeCollectionChuyenBay.Count; i++)
                {
                    ChuyenBay chuyenBay = new ChuyenBay();

                    HtmlAgilityPack.HtmlNode nChuyenbay = nodeCollectionChuyenBay[i];

                    chuyenBay.MaChuyenBay = AirMekongUtils.GetCodeFlight(nChuyenbay.ChildNodes[1].InnerText.Trim());
                    chuyenBay.DiemDiID = DiaDiemDAO.SelectByCode(diemDi).DiaDiemID;
                    chuyenBay.DiemDenID = DiaDiemDAO.SelectByCode(diemDen).DiaDiemID;
                    chuyenBay.NgayDi = ngayDi;
                    chuyenBay.HangHangKhongID = maHangKhong;
                    chuyenBay.DiemDung = "";
                    
                    
                    //Lấy thông tin điểm dừng
                    string maChuyenBay = chuyenBay.MaChuyenBay;
                    int index = maChuyenBay.IndexOf("*");
                    int soDiemDung = 0;

                    while(index!= -1)
                    {
                        soDiemDung += 1;

                        HtmlAgilityPack.HtmlNode nDiemDung = nChuyenbay.ChildNodes[1].ChildNodes[soDiemDung];

                        string tenDiemDung = AirMekongUtils.GetStopStation(nDiemDung.Attributes["onmouseover"].Value);

                        maChuyenBay = maChuyenBay.Remove(index, 1);
                        index = maChuyenBay.IndexOf("*");

                        chuyenBay.DiemDung += tenDiemDung + ",";
                    }

                    int chuyenBayID = ChuyenBayDAO.Insert(chuyenBay);

                    if (chuyenBayID > 0)
                    {
                       
                        ChiTietChuyenBay chiTietChuyenBay = new ChiTietChuyenBay();

                        chiTietChuyenBay.ThoiGianDi = nChuyenbay.ChildNodes[3].InnerText.Trim();
                        chiTietChuyenBay.ThoiGianDen = nChuyenbay.ChildNodes[5].InnerText.Trim();
                        chiTietChuyenBay.ChuyenBayID = chuyenBay.ChuyenBayID;
                        chiTietChuyenBay.DiemDiID = chuyenBay.DiemDiID;
                        chiTietChuyenBay.DiemDenID = chuyenBay.DiemDenID;

                        int chiTietChuyenBayID = ChiTietChuyenBayDAO.Insert(chiTietChuyenBay);

                        int tmp = 7;
                        int loaiGiaVe = LoaiGiaVeDAO.SelectByTypeName(Constants.AIRMEKONG_FIRST_TYPE_TICKET_NAME).LoaiGiaVeID;

                        for (int j = 0; j < 5; j++)
                        {
                            GiaVe giaVe = new GiaVe();

                            giaVe.LoaiGiaVeID = loaiGiaVe;
                            loaiGiaVe++;

                            giaVe.Gia = (decimal)AirMekongUtils.LayGiaVe(nChuyenbay, tmp);
                            giaVe.ChuyenBayID = chuyenBayID;
                            giaVe.ChoNgoi = "";
                            tmp = tmp + 2;

                            GiaVeDAO.Insert(giaVe);
                        }
                        
                    }
                }
            }

        }


        private string TaoPostString(string diemDi, string diemDen, int ngayDi, string thangNamDi)
        {
            string postString = "__EVENTTARGET=" +
       "&__EVENTARGUMENT=" +
       "&__VIEWSTATE=/wEPDwUBMGRk77h9CNekodLMZhdJu3riPx9ebN8=" +
       "&pageToken=" +
       "&ControlGroupSearchInfoView$AvailabilitySearchInputSearchInfoView$RadioButtonMarketStructure=OneWay" +
       "&originStation1=" + diemDi +
       "&ControlGroupSearchInfoView$AvailabilitySearchInputSearchInfoView$TextBoxMarketOrigin1=" + diemDi +
       "&destinationStation1=" + diemDen +
       "&ControlGroupSearchInfoView$AvailabilitySearchInputSearchInfoView$TextBoxMarketDestination1=" + diemDen +
       "&ControlGroupSearchInfoView$AvailabilitySearchInputSearchInfoView$DropDownListMarketDay1=" + ngayDi +
       "&ControlGroupSearchInfoView$AvailabilitySearchInputSearchInfoView$DropDownListMarketMonth1=" + thangNamDi +
       "&ControlGroupSearchInfoView$AvailabilitySearchInputSearchInfoView$DropDownListMarketDateRange1=0|4" +
       "&originStation2=" +
       "&ControlGroupSearchInfoView$AvailabilitySearchInputSearchInfoView$TextBoxMarketOrigin2=Điểm đi..." +
       "&destinationStation2=" +
       "&ControlGroupSearchInfoView$AvailabilitySearchInputSearchInfoView$TextBoxMarketDestination2=Điểm đến..." +
       "&ControlGroupSearchInfoView$AvailabilitySearchInputSearchInfoView$DropDownListMarketDay2=20" +
       "&ControlGroupSearchInfoView$AvailabilitySearchInputSearchInfoView$DropDownListMarketMonth2=2012-12" +
       "&ControlGroupSearchInfoView$AvailabilitySearchInputSearchInfoView$DropDownListMarketDateRange2=0|4" +
       "&ControlGroupSearchInfoView$AvailabilitySearchInputSearchInfoView$DropDownListPassengerType_ADT=1" +
       "&ControlGroupSearchInfoView$AvailabilitySearchInputSearchInfoView$DropDownListPassengerType_CHD=0" +
       "&ControlGroupSearchInfoView$AvailabilitySearchInputSearchInfoView$DropDownListPassengerType_INFANT=0" +
       "&ControlGroupSearchInfoView$AvailabilitySearchInputSearchInfoView$DropDownListSearchBy=columnView" +
       "&ControlGroupSearchInfoView$AvailabilitySearchInputSearchInfoView$ButtonSubmit=Tìm chuyến bay";

            return postString;
        }

        //Gửi yêu cầu rút trích trên trang web
        public HtmlAgilityPack.HtmlDocument GuiYeuCauLenWeb(string postString)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.strURL);

            request.ProtocolVersion = HttpVersion.Version10;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            request.KeepAlive = true;
            CookieContainer cookieJar = new CookieContainer();
            request.CookieContainer = cookieJar;

            byte[] postBytes = Encoding.UTF8.GetBytes(postString);

            request.ContentLength = postBytes.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.WriteTimeout = 10000;
            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            string codeHtml = new StreamReader(response.GetResponseStream()).ReadToEnd();

            HtmlAgilityPack.HtmlDocument dom = new HtmlAgilityPack.HtmlDocument();
            dom.OptionOutputAsXml = true;
            dom.LoadHtml(codeHtml);

            return dom;
        }

    }
}
